<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-tabs type="border-card">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="showDialog=true"
        >新增角色</el-button>
        <!-- <el-button size="small" type="primary" @click="tianjia">编辑</el-button> -->
        <el-tab-pane label="角色管理">
          <el-table
            v-loading="loading"
            :data="tableData"
            border
            style="width: 100%"
            height="250"
            stripe
            header-align="cnter"
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              sortable
              width="120px"
            />
            <el-table-column
              prop="name"
              label="名称"
              align="center"
              sortable
              width="240px"
            />
            <el-table-column
              prop="description"
              label="描述"
              align="center"
            />
            <el-table-column
              prop="address"
              label="操作"
              align="center"
            >
              <template slot-scope="{row}">
                <el-button size="small" type="success" @click="assignPerm(row.id)">分配权限</el-button>
                <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteRole(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- // 分页 -->
          <el-row type="flex" justify="center" style="margin-top: 20px;" align="middle">
            <el-pagination
              :current-page="page.page"
              :page-size="page.pagesize"
              :total="page.total"
              :page-sizes="[10, 20, 30, 40]"
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="changePage"
              @size-change="genxing"
            />
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="公司信息">
          <el-alert
            title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
            type="info"
            show-icon
            :closable="false"
          />
          <el-form label-width="120px" style="margin-top:30px" label-position="right" :model="formData">
            <el-form-item label="公司名称">
              <el-input v-model="formData.name" disabled style="width:400px" />
            </el-form-item>
            <el-form-item label="公司地址">
              <el-input v-model="formData.companyAddress" disabled style="width:400px" />
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="formData.mailbox" disabled style="width:400px" />
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="formData.remarks" disabled style="width:400px" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <!-- // 放置一个弹层 -->
      <el-dialog title="编辑弹层" :visible="showDialog" @close="btnCancel">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>

      <el-dialog title="分配权限" :visible="showPermDialog" @close="btnPermCancel">
        <!-- 权限是一颗树 -->
        <!-- 将数据绑定到组件上 -->
        <!-- check-strictly 如果为true 那表示父子勾选时  不互相关联 如果为false就互相关联 -->
        <!-- id作为唯一标识 -->
        <el-tree
          ref="permTree"
          :data="permData"
          :props="defaultProps"
          :show-checkbox="true"
          :check-strictly="true"
          :default-expand-all="true"
          :default-checked-keys="selectCheck"
          node-key="id"
        />
        <!-- 确定 取消 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="small" @click="btnPermOK">确定</el-button>
            <el-button size="small" @click="btnPermCancel">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoleList, getCompanyInfo, deleteRole, assignPerm, updateRole, getRoleDetail, addRole } from '@/api/setting'
// 转换树形的函数
import { transListToTreeData } from '@/utils'
// 获取权限
import { getPermissionList } from '@/api/permisson'
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      showPermDialog: false, // 控制分配权限弹层的显示后者隐藏
      defaultProps: {
        label: 'name'
      },
      permData: [], // 专门用来接收权限数据 树形数据
      selectCheck: [], // 定义一个数组来接收 已经选中的节点
      roleId: null, // 用来记录分配角色的id
      tableData: [],
      currentPage4: 4,
      // 加载
      loading: false,
      page: {
        // 放置页码及相关数据
        page: 1, // 页数
        pagesize: 10, // 显示页数
        total: 0 // 记录总数
      },
      formData: {},
      // 表单的显示与隐藏
      showDialog: false,
      // 专门接收新增或者编辑的编辑的表单数据
      roleForm: {},
      rules: {
        // name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters(['companyId'])
  },
  created() {
    this.getRoleList() // 获取角色列表
    this.getCompanyInfo()
    this.changePage()
  },
  methods: {
    async getRoleList() {
      const { total, rows } = await getRoleList(this.page)
      this.page.total = total
      this.tableData = rows
    },
    changePage(val) {
      console.log(`当前页: ${val}`)
      this.page.page = val
      this.getRoleList()
    },
    // 获取的公司的信息
    async getCompanyInfo() {
      this.formData = await getCompanyInfo(this.companyId)
    },
    // 调用删除的接口实现删除
    deleteRole(id) {
      this.$confirm('确认删除该角色吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteRole(id)
        this.getRoleList() // 重新加载数据
        this.$message.success('删除角色成功')
      }).catch((error) => {
        this.$message.success(error)
      })
    },
    async editRole(id) {
    // 数据的回显
      this.roleForm = await getRoleDetail(id)// 先获取数据
      this.showDialog = true
    },
    // 更新页数
    genxing(val) {
      this.page.pagesize = val
      this.getRoleList() // 重新加载数据
    },
    btnCancel() {
      // 清除输入框
      this.roleForm = {
        name: '',
        description: ''
      }
      // 移除校验
      this.$refs.roleForm.resetFields()
      // 关闭窗口
      this.showDialog = false
    },
    async btnOK() {
      try {
        await this.$refs.roleForm.validate()
        if (this.roleForm.id) {
          await updateRole(this.roleForm)
        } else {
          //  新增业务
          await addRole(this.roleForm)
        }
        // 重新拉取数据
        this.getRoleList()
        this.$message.success('操作成功')
        // 关闭窗口 会触发close事件
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    // 分配权限
    async assignPerm(id) {
      this.permData = transListToTreeData(await getPermissionList(), '0') // 转化list到树形数据
      this.roleId = id
      // 应该去获取 这个id的 权限点
      // 有id 就可以 id应该先记录下来
      const { permIds } = await getRoleDetail(id) // permIds是当前角色所拥有的权限点数据
      this.selectCheck = permIds // 将当前角色所拥有的权限id赋值
      this.showPermDialog = true
    },
    // 取消
    btnPermCancel() {
      this.selectCheck = [] // 重置数据
      this.showPermDialog = false
    },
    async  btnPermOK() {
      // 调用el-tree的方法
      // console.log(this.$refs.permTree.getCheckedKeys())
      await assignPerm({ permIds: this.$refs.permTree.getCheckedKeys(), id: this.roleId })
      this.$message.success('分配权限成功')
      this.showPermDialog = false
    }
    /*     async tianjia() {
      for (let i = 1; i < 20; i++) {
        this.currentPage4++
        await addRole({ name: `测试${this.currentPage4}`,
          description: '1212' })
        this.getRoleList()
      }
    } */
  }
}
</script>

<style lang="scss" scoped>
.el-tabs{
box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
}
.el-tab-pane{
  margin-top: 20px;
}
</style>
